package com.hui.qiniucloud.mapper;

import com.hui.qiniucloud.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 用户表 Mapper 接口
 * </p>
 *
 * @author huihui
 * @since 2025-09-28
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

    /**
     * 根据用户名查询用户（包括逻辑删除的）
     */
    @Select("SELECT * FROM user WHERE username = #{username}")
    User selectByUsernameIncludeDeleted(@Param("username") String username);

    /**
     * 根据用户名查询活跃用户
     */
    @Select("SELECT * FROM user WHERE username = #{username} AND deleted = 0")
    User selectActiveByUsername(@Param("username") String username);

    /**
     * 根据邮箱查询活跃用户
     */
    @Select("SELECT * FROM user WHERE email = #{email} AND deleted = 0")
    User selectActiveByEmail(@Param("email") String email);

    /**
     * 根据手机号查询活跃用户
     */
    @Select("SELECT * FROM user WHERE phone = #{phone} AND deleted = 0")
    User selectActiveByPhone(@Param("phone") String phone);

    /**
     * 更新用户最后登录信息
     */
    @Update("UPDATE user SET last_login_time = #{loginTime}, last_login_ip = #{loginIp}, updated_time = NOW() WHERE id = #{userId} AND deleted = 0")
    int updateLastLoginInfo(@Param("userId") Long userId, @Param("loginTime") LocalDateTime loginTime, @Param("loginIp") String loginIp);

    /**
     * 查询所有活跃用户
     */
    @Select("SELECT * FROM user WHERE deleted = 0 ORDER BY created_time DESC")
    List<User> selectAllActive();

    /**
     * 根据关键词搜索用户（用户名、昵称、邮箱）
     */
    @Select("SELECT * FROM user WHERE deleted = 0 AND (username LIKE CONCAT('%', #{keyword}, '%') OR nickname LIKE CONCAT('%', #{keyword}, '%') OR email LIKE CONCAT('%', #{keyword}, '%')) ORDER BY created_time DESC")
    List<User> searchByKeyword(@Param("keyword") String keyword);
}
